<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <a href="/home">首页</a>
    <a href="/about">关于我们</a>
    <a href="/test">其他</a>
    <hr>
    <div id="result"></div>
    <script>
        //获取所有的 a 标签
        let links = document.querySelectorAll('a');
        let result = document.getElementById('result');

        //绑定事件
        links.forEach(a => {
            //绑定事件
            a.addEventListener('click', function(e){
                //阻止默认行为
                e.preventDefault();
                //修改 url 
                history.pushState(null, '', e.target.href);
                //根据 url 路径切换显示的内容
                // console.log(location);
                switch (location.pathname) {
                    case '/home':
                        result.innerHTML = '<h2>首页</h2>'
                        break;
                    case '/about':
                        result.innerHTML = '<h2>关于我们</h2>'
                        break;
                    default:
                        result.innerHTML = '<h2>默认内容</h2>'
                        break;
                }
            });
        });
    
        //事件  弹出状态的时候触发该事件, 点击后退与前进. 功能与 hashchange 的功能相似
        window.addEventListener('popstate', function(e){
            // console.log(e);
            //根据页面 url 的路径切换显示内容即可
            switch (location.pathname) {
                    case '/home':
                        result.innerHTML = '<h2>首页</h2>'
                        break;
                    case '/about':
                        result.innerHTML = '<h2>关于我们</h2>'
                        break;
                    default:
                        result.innerHTML = '<h2>默认内容</h2>'
                        break;
                }
        })
    </script>
</body>
</html>